import React, { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { AtRate } from 'taro-ui'
import {Image, View, Text, Textarea} from '@tarojs/components'
import { commentUploadImgServer } from '@/services/comment';
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/rate.scss";
import './index.scss'

export default function VideoComment() {
  const [query,setQuery] = useState({})
  const [info,setInfo] = useState({})
  const [uploadMap,setUploadMap] = useState({})
  const [commentId,setCommentId] = useState('')
  const [state, updateState] = useState({
    files: [],
  });
  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
  };
  useEffect(()=>{
    const {router} = Taro.getCurrentInstance()
    setCommentId(router?.params?.commentId)
    Taro.$get('/cinema-app/api/v1/film/filmInfo',{id:router.params.filmId},'1').then(res=>{
      if(res.code == '1'){
        setInfo(res.content)
        Taro.setNavigationBarTitle({
          title:res.content?.filmNickName
        })
      }
    })
    if(router.params.editId){
      Taro.$get('/social/score/getCommentDetail',{topicId:router.params.editId,appId:'cinema_film'},'1').then(res=>{
        if(res.code == '1'){
          setQuery({
            score:res.content.score,
            content:res.content.comment
          })
        }
      })
    }
  },[])
  const handleChoiseImg = () => { ///  选择图片
    Taro.chooseImage({
      count: 9 - state.files.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if (state.files.length + res.tempFilePaths.length > 9) {
          Taro.showToast({
            title: `最多上传9张图片`,
            duration: 1000,
            icon: 'none',
          });
        } else {
          setState({ files: state.files.concat(res.tempFilePaths) });
        }
      },
    });
  }
  return (
    <View className='video-comment'>
      <View className="comment-rate">
        <View className="rate-label">评分</View>
        <AtRate value={query.score} onChange={e=>{
          setQuery({...query,score:e})
        }} />
      </View>
      <Textarea style={{width:'100%'}} maxlength={500} value={query.content} disabled={Taro.getCurrentInstance().router.params?.editId} placeholder='请输入内容' onInput={e=>{
        setQuery({...query,content:e.detail.value})
      }} />
      <View className="comment-imgs">
        {state.files?.map((res,idx)=>{
          return <View key={res} className="imgs-item"><Image src={res} className='img' mode='aspectFill' /> <Text onClick={()=>{
            if(Taro.getCurrentInstance().router.params?.editId) return;
            setTimeout(() => {
              state.files.splice(idx, 1);
              setState({
                files: state.files,
              });
            }, 0);
          }} className='at-icon at-icon-close-circle'></Text></View>
        })}
        {Taro.getCurrentInstance().router.params?.editId?null:<View className="imgs-upload" onClick={()=>{handleChoiseImg()}}><Text style={{fontSize:20}}>+</Text> 添加图片</View>}
      </View>

      <View className="comment-button" onClick={async ()=>{
        Taro.showLoading({title:'加载中...'})
        let imgs = {};
        let files = uploadMap.files || []
        const imgUrls = state.files || [];
        for (let file of imgUrls) {
          if (!!uploadMap[file]) {
            //避免重复上传
            imgs[file] = uploadMap[file];
            continue;
          }
          const fileRes = await commentUploadImgServer(file);
          if (fileRes.code == 1 && fileRes.content) {
            imgs[file] = fileRes.content;
            files.push(fileRes.content)
          }else{
            Taro.showToast({
              title:'上传失败',
              icon:'none'
            })
            return;
          }
        }
        const data = {
          imgUrls:files.length?files:undefined,
          ...query,
          score:query.score*2,
          userSource:Taro.getStorageSync('userSource'),
          cityName:Taro.getStorageSync('cityInfo').cityName,
          extra:JSON.stringify(info),
          title:info.filmNickName
        }
        if(commentId){
          Object.assign(data,{
            commentId
          })
        }else{
          Object.assign(data,{
            appId:'cinema_film',
            topicId:info.id,
          })
        }
        Taro.showModal({
          title:'发布',
          content:"确定发布评论吗?",
          success:res=>{
            if(res.confirm){
              Taro.$post('/social/score/V1',data,'1').then(ret=>{
                if(ret.code == '1'){
                  Taro.$toast('提交成功','success')
                  setTimeout(() => {
                    Taro.navigateBack()
                  }, 1000);
                }else{
                  Taro.$toast(ret.message)
                }
              })
            }
          }
        })
      }}>发布</View>
    </View>
  )
}
